<template>
  <div class="retail-outbound-container">
    <!-- 搜索栏 -->
    <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
      <el-input v-model="searchParams.outboundNo" style="width: 240px; padding-right: 15px;" placeholder="请输入出库单号" />
      <el-select v-model="searchParams.memberId" placeholder="请选择会员" clearable style="width: 200px; margin-right: 15px;">
        <el-option
            v-for="member in memberList"
            :key="member.id"
            :label="member.name"
            :value="member.id"
        />
      </el-select>
      <el-select v-model="searchParams.warehouseId" placeholder="请选择仓库" clearable style="width: 200px; margin-right: 15px;">
        <el-option
            v-for="warehouse in warehouseList"
            :key="warehouse.id"
            :label="warehouse.name"
            :value="warehouse.id"
        />
      </el-select>
      <el-icon @click="getRetailOutboundList()" style="margin-left: 20px; height: 25px; width: 25px;">
        <Search />
      </el-icon>
      <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
        <Refresh />
      </el-icon>
      <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">新增零售出库</el-button>
    </div>

    <!-- 零售出库表格 -->
    <el-table :data="retailOutboundList" style="width: 100%" stripe border="true" v-loading="loading">
      <el-table-column label="序号" width="80px" #default="scope" align="center">
        {{ scope.$index + 1 }}
      </el-table-column>
      <el-table-column prop="outboundNo" label="出库单号" width="180" align="center" />
      <el-table-column prop="memberName" label="会员名称" width="120" align="center" />
      <el-table-column prop="warehouseName" label="仓库名称" width="150" align="center" />
      <el-table-column prop="outboundDate" label="出库日期" width="150" align="center">
        <template #default="scope">
          {{ formatDateYMD(scope.row.outboundDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" #default="scope" align="center">
        <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
        <span v-if="scope.row.status == 1" style="color: blue;">待完成</span>
        <span v-if="scope.row.status == 2" style="color: green;">已完成</span>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="200" align="center" />
      <el-table-column label="操作" width="300px" fixed="right" align="center" #default="scope">
        <el-button type="primary" plain @click="viewRetailOutboundDetails(scope.row.id)">详情</el-button>
        <el-button type="warning" plain @click="showEditDialog(scope.row)" v-if="scope.row.status !== 2">修改</el-button>
        <el-button type="success" plain @click="completeRetailOutbound(scope.row.id)" v-if="scope.row.status === 1">完成出库</el-button>
        <el-button type="danger" plain @click="handleDeleteRetailOutbound(scope.row.id)" v-if="scope.row.status === 0">删除</el-button>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
      <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                     :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑零售出库' : '新增零售出库'" width="1150px"
               :before-close="handleDialogClose" :close-on-click-modal="false" style="left: 90px">
      <el-form :model="retailOutbound" :rules="formRules" ref="retailOutboundForm" label-width="120px" style="padding: 15px 0;">
        <el-form-item label="出库单号" prop="outboundNo" v-if="isEdit">
          <el-input v-model="retailOutbound.outboundNo" disabled placeholder="系统自动生成" />
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-select v-model="retailOutbound.status" placeholder="请选择状态" style="width: 100%">
            <el-option :label="'草稿'" :value="0" />
            <el-option :label="'待完成'" :value="1" />
            <el-option :label="'已完成'" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="会员" prop="memberId">
          <el-select v-model="retailOutbound.memberId" placeholder="请选择会员" clearable style="width: 100%">
            <el-option
                v-for="member in memberList"
                :key="member.id"
                :label="member.name"
                :value="member.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select v-model="retailOutbound.warehouseId" placeholder="请选择仓库" clearable style="width: 100%">
            <el-option
                v-for="warehouse in warehouseList"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出库日期" prop="outboundDate">
          <el-date-picker
              v-model="retailOutbound.outboundDate"
              type="date"
              placeholder="请选择出库日期"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="retailOutbound.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>

        <!-- 商品明细管理 -->
        <el-form-item label="商品明细">
          <div class="items-container">
            <div class="items-header">
              <h4>出库商品明细</h4>
              <el-button type="primary" size="small" @click="addItem">添加商品</el-button>
            </div>
            <el-table :data="retailOutbound.items || []" style="width: 100%" stripe border="true">
              <el-table-column label="序号" width="60px" #default="scope" align="center">
                {{ scope.$index + 1 }}
              </el-table-column>
              <el-table-column label="产品名称" width="200px">
                <template #default="scope">
                  <div v-if="isEdit && scope.row.productId && scope.row.productName">
                    <span>{{ scope.row.productName }}</span>
                    <el-button type="text" size="small" @click="editProduct(scope.row)" style="margin-left: 10px;">修改</el-button>
                  </div>
                  <el-select v-else v-model="scope.row.productId" placeholder="请选择产品" @change="onProductChange(scope.row)">
                    <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="数量" width="150px">
                <template #default="scope">
                  <el-input-number v-model="scope.row.quantity" :min="1" :precision="0" :step="1" />
                </template>
              </el-table-column>
              <el-table-column label="单价" width="150px">
                <template #default="scope">
                  <el-input-number v-model="scope.row.unitPrice" :min="1" :precision="0" :step="1" />
                </template>
              </el-table-column>
              <el-table-column label="小计" width="120px" align="center">
                <template #default="scope">
                  {{ ((scope.row.quantity || 0) * (scope.row.unitPrice || 0)).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="备注" width="150px">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="备注" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100px" align="center">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose" size="default">取消</el-button>
          <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 零售出库详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="零售出库详情" width="800px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
      <div v-if="currentRetailOutbound" class="retail-outbound-detail">
        <div class="detail-header">
          <p><span class="label">出库单号：</span>{{ currentRetailOutbound.outboundNo }}</p>
          <p><span class="label">会员名称：</span>{{ currentRetailOutbound.memberName }}</p>
          <p><span class="label">仓库名称：</span>{{ currentRetailOutbound.warehouseName }}</p>
          <p><span class="label">出库日期：</span>{{ formatDateYMD(currentRetailOutbound.outboundDate) }}</p>
          <p><span class="label">出库状态：</span>
            <span v-if="currentRetailOutbound.status == 0" style="color: gray;">草稿</span>
            <span v-if="currentRetailOutbound.status == 1" style="color: blue;">待完成</span>
            <span v-if="currentRetailOutbound.status == 2" style="color: green;">已完成</span>
          </p>
          <p><span class="label">备注：</span>{{ currentRetailOutbound.remark }}</p>
        </div>

        <div class="detail-items">
          <h3>商品明细</h3>
          <el-table :data="currentRetailOutbound.items || []" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80px" #default="scope" align="center">
              {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" width="180" align="center" />
            <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
            <el-table-column prop="quantity" label="数量" width="120" align="center" />
            <el-table-column prop="unitPrice" label="单价" width="120" align="center">
              <template #default="scope">
                ¥{{ scope.row.unitPrice }}
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120" align="center">
              <template #default="scope">
                ¥{{ ((scope.row.quantity || 0) * (scope.row.unitPrice || 0)).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="120" align="center" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, computed } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getRetailOutboundPage,
  createRetailOutbound,
  updateRetailOutbound,
  deleteRetailOutbound,
  completeRetailOutbound as completeRetailOutboundApi,
  getRetailOutboundWithDetails
} from '@/api/retail/retail_outbound';
import { getMemberList } from '@/api/retail/retail_outbound';
import { getWarehouseList, getProductList } from '@/api/warehouse/warehouse';
// 日期格式化：仅显示 YYYY-MM-DD
function formatDateYMD(value) {
  if (!value) return '';
  // 已是 YYYY-MM-DD
  if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
  // 形如 2025-08-11T16:49:50 或带毫秒/时区
  if (typeof value === 'string') {
    const m = value.match(/^(\d{4}-\d{2}-\d{2})/);
    if (m) return m[1];
  }
  try {
    const d = new Date(value);
    if (!isNaN(d.getTime())) {
      const y = d.getFullYear();
      const mm = String(d.getMonth() + 1).padStart(2, '0');
      const dd = String(d.getDate()).padStart(2, '0');
      return `${y}-${mm}-${dd}`;
    }
  } catch (_) {}
  return String(value);
}

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 零售出库列表数据
const retailOutboundList = ref([]);

// 会员列表数据（用于选择）
const memberList = ref([]);

// 仓库列表数据（用于选择）
const warehouseList = ref([]);

// 产品列表数据（用于选择）
const productList = ref([]);

// 搜索参数
const searchParams = ref({
  outboundNo: '',
  memberId: '',
  warehouseId: '',
  startDate: '',
  endDate: ''
});

// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 对话框状态
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);

// 当前操作的零售出库
const retailOutbound = ref({});
const currentRetailOutbound = ref(null);

// 加载状态
const loading = ref(false);

// 统一解包工具
function unwrap(res) {
  return (res && res.data !== undefined) ? res.data : res;
}

function unwrapPageRecords(payload) {
  const data = unwrap(payload);
  if (data && Array.isArray(data.records)) {
    return { records: data.records, total: Number(data.total) || data.records.length };
  }
  if (Array.isArray(data)) {
    return { records: data, total: data.length };
  }
  return { records: [], total: 0 };
}

// 表单验证规则
const formRules = ref({
  memberId: [
    { required: true, message: '请选择会员', trigger: 'change' }
  ],
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  outboundDate: [
    { required: true, message: '请选择出库日期', trigger: 'change' }
  ]
});

// 获取零售出库列表
function getRetailOutboundList() {
  loading.value = true;
  // 构建分页参数
  const pageParams = {
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    outboundNo: searchParams.value.outboundNo,
    memberId: searchParams.value.memberId,
    warehouseId: searchParams.value.warehouseId,
    startDate: searchParams.value.startDate,
    endDate: searchParams.value.endDate
  };

  getRetailOutboundPage(pageParams).then(res => {
    const page = unwrapPageRecords(res);
    retailOutboundList.value = page.records;
    pagination.value.total = page.total;
  }).catch(error => {
    ElMessage.error('获取零售出库列表失败');
    console.error('获取零售出库列表失败:', error);
  }).finally(() => {
    loading.value = false;
  });
}

// 获取会员列表（用于选择）
function fetchMembers() {
  getMemberList().then(res => {
    const data = unwrap(res);
    memberList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
  }).catch(error => {
    ElMessage.error('获取会员列表失败');
    console.error('获取会员列表失败:', error);
  });
}

// 获取仓库列表（用于选择）
function fetchWarehouses() {
  getWarehouseList().then(res => {
    const data = unwrap(res);
    warehouseList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
  }).catch(error => {
    ElMessage.error('获取仓库列表失败');
    console.error('获取仓库列表失败:', error);
  });
}

// 获取产品列表（用于选择）
function fetchProducts() {
  getProductList().then(res => {
    const data = unwrap(res);
    productList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
  }).catch(error => {
    ElMessage.error('获取产品列表失败');
    console.error('获取产品列表失败:', error);
  });
}

// 重置搜索参数
function resetSearchParams() {
  searchParams.value = {
    outboundNo: '',
    memberId: '',
    warehouseId: '',
    startDate: '',
    endDate: ''
  };
  getRetailOutboundList();
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  getRetailOutboundList();
}

const handleCurrentChange = (val) => {
  pagination.value.pageNum = val;
  getRetailOutboundList();
}

// 显示创建对话框
function showAddDialog() {
  isEdit.value = false;
  retailOutbound.value = {
    items: [],
    status: 0,
    outboundDate: new Date().toISOString().split('T')[0],
    totalAmount: 0
  };
  dialogVisible.value = true;
  // 重置表单
  if (proxy.$refs.retailOutboundForm) {
    proxy.$refs.retailOutboundForm.resetFields();
  }
}

// 显示编辑对话框
function showEditDialog(row) {
  isEdit.value = true;
  // 先显示对话框，避免用户等待
  dialogVisible.value = true;

  // 获取零售出库的完整信息（包含商品明细）
  getRetailOutboundWithDetails(row.id).then(res => {
    const data = unwrap(res);
    if (data) {
      // 深拷贝数据，避免直接修改原数据
      retailOutbound.value = JSON.parse(JSON.stringify(data));
      if (!retailOutbound.value.items) {
        retailOutbound.value.items = [];
      }
    } else {
      // 如果获取失败，使用基础数据
      retailOutbound.value = JSON.parse(JSON.stringify(row));
      if (!retailOutbound.value.items) {
        retailOutbound.value.items = [];
      }
      ElMessage.warning('获取商品明细失败，请刷新后重试');
    }
  }).catch(error => {
    // 如果获取失败，使用基础数据
    retailOutbound.value = JSON.parse(JSON.stringify(row));
    if (!retailOutbound.value.items) {
      retailOutbound.value.items = [];
    }
    ElMessage.error('获取商品明细失败');
    console.error('获取商品明细失败:', error);
  });
}

// 关闭对话框
function handleDialogClose() {
  dialogVisible.value = false;
  // 重置表单
  if (proxy.$refs.retailOutboundForm) {
    proxy.$refs.retailOutboundForm.resetFields();
  }
}

// 添加商品明细
function addItem() {
  if (!retailOutbound.value.items) {
    retailOutbound.value.items = [];
  }
  retailOutbound.value.items.push({
    productId: null,
    quantity: 1,
    unitPrice: 0,
    remark: ''
  });
}

// 移除商品明细
function removeItem(index) {
  retailOutbound.value.items.splice(index, 1);
  calculateTotal();
}

// 产品选择变化处理
function onProductChange(item) {
  const product = productList.value.find(p => p.id === item.productId);
  if (product) {
    item.productName = product.name;
    item.productCode = product.code;
  }
  calculateTotal();
}

// 编辑产品（显示选择器）
function editProduct(item) {
  // 清除产品信息，显示选择器
  item.productId = null;
  item.productName = null;
  item.productCode = null;
}

// 取消编辑产品（恢复显示）
function cancelEditProduct(item) {
  // 这里可以添加逻辑来恢复之前的产品信息
  // 暂时简单处理，用户需要重新选择
}

// 计算总金额
function calculateTotal() {
  if (retailOutbound.value.items && retailOutbound.value.items.length > 0) {
    const total = retailOutbound.value.items.reduce((sum, item) => {
      return sum + ((item.quantity || 0) * (item.unitPrice || 0));
    }, 0);
    retailOutbound.value.totalAmount = total;
  } else {
    retailOutbound.value.totalAmount = 0;
  }
}

// 提交表单
function submitForm() {
  // 验证商品明细
  if (!retailOutbound.value.items || retailOutbound.value.items.length === 0) {
    ElMessage.warning('请至少添加一个商品明细');
    return;
  }

  // 验证商品是否选择完整
  for (let item of retailOutbound.value.items) {
    if (!item.productId) {
      ElMessage.warning('请选择所有商品');
      return;
    }
    if (!item.quantity || item.quantity <= 0) {
      ElMessage.warning('请输入有效的商品数量');
      return;
    }
    if (!item.unitPrice || item.unitPrice < 0) {
      ElMessage.warning('请输入有效的商品单价');
      return;
    }
  }

  // 计算总金额
  calculateTotal();

  proxy.$refs.retailOutboundForm.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 更新零售出库
        updateRetailOutbound(retailOutbound.value).then(res => {
          ElMessage.success('零售出库更新成功');
          handleDialogClose();
          getRetailOutboundList();
        }).catch(error => {
          ElMessage.error('零售出库更新失败');
          console.error('更新失败:', error);
        });
      } else {
        // 创建零售出库
        createRetailOutbound(retailOutbound.value).then(res => {
          ElMessage.success('零售出库创建成功');
          handleDialogClose();
          getRetailOutboundList();
        }).catch(error => {
          ElMessage.error('零售出库创建失败');
          console.error('创建失败:', error);
        });
      }
    } else {
      ElMessage.warning('请完善零售出库信息并确保格式正确');
      return false;
    }
  });
}

// 查看零售出库详情
function viewRetailOutboundDetails(id) {
  getRetailOutboundWithDetails(id).then(res => {
    const data = unwrap(res);
    currentRetailOutbound.value = data || null;
    detailDialogVisible.value = true;
  }).catch(error => {
    ElMessage.error('获取零售出库详情失败');
    console.error('获取详情失败:', error);
  });
}

// 关闭详情对话框
function handleDetailDialogClose() {
  detailDialogVisible.value = false;
  currentRetailOutbound.value = null;
}

// 完成零售出库
function completeRetailOutbound(id) {
  ElMessageBox.confirm(
      '确定要完成该零售出库吗？完成后将自动调整库存。',
      '完成确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    completeRetailOutboundApi(id).then(() => {
      ElMessage.success('零售出库已完成，库存已调整');
      getRetailOutboundList();
    }).catch(error => {
      ElMessage.error('完成零售出库失败');
      console.error('完成失败:', error);
    });
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
}

// 删除零售出库
function handleDeleteRetailOutbound(id) {
  ElMessageBox.confirm(
      '确定要删除该零售出库吗？此操作不可撤销。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    deleteRetailOutbound(id).then(res => {
      ElMessage.success('零售出库删除成功');
      getRetailOutboundList();
    }).catch(error => {
      ElMessage.error('零售出库删除失败');
      console.error('删除失败:', error);
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 页面加载时获取零售出库列表、会员列表、仓库列表和产品列表
onMounted(() => {
  getRetailOutboundList();
  fetchMembers();
  fetchWarehouses();
  fetchProducts();
});
</script>

<style scoped>
.retail-outbound-container {
  padding: 20px;
}

.search-bar {
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar .el-input,
.search-bar .el-select,
.search-bar .el-date-picker {
  margin-right: 15px;
}

.search-bar .el-button {
  margin-left: 15px;
}

.retail-outbound-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-header p {
  margin: 8px 0;
}

.label {
  font-weight: bold;
  display: inline-block;
  width: 100px;
}

.detail-items h3 {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.items-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
}

.items-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
}

.items-header h4 {
  margin: 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}
</style>
